package me.wsj.diybinder.proxy;

import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;

import java.util.List;

import me.wsj.diybinder.Book;
import me.wsj.diybinder.server.BookManager;
import me.wsj.diybinder.server.Stub;

/**
 * 客户端对Stub的代理对象
 */
public class Proxy implements BookManager {

    private static final String DESCRIPTOR = "com.wsj.ipc.server.BookManager";

    private IBinder remote;

    public Proxy(IBinder remote) {
        // 相当于是stub对象
        this.remote = remote;
    }

    public String getInterfaceDescriptor() {
        return DESCRIPTOR;
    }

    @Override
    public List<Book> getBooks() throws RemoteException {
        Parcel data = Parcel.obtain();
        Parcel replay = Parcel.obtain();
        List<Book> result;

        try {
            // 将DESCRIPTOR作为token识别是哪个Binder对象
            data.writeInterfaceToken(DESCRIPTOR);
            // flag可以设置为oneway来实现异步调用
            // 进入Binder的transact方法中，然后会执行Stub的onTransact
            // 方法名以编号形式传递
            remote.transact(Stub.TRANSAVTION_getBooks, data, replay, 0);
            replay.readException();
            // 获取结果并返回
            result = replay.createTypedArrayList(Book.CREATOR);
        } finally {
            replay.recycle();
            data.recycle();
        }
        return result;
    }

    @Override
    public void addBook(Book book) throws RemoteException {

        Parcel data = Parcel.obtain();
        Parcel replay = Parcel.obtain();

        try {
            data.writeInterfaceToken(DESCRIPTOR);
            if (book != null) {
                data.writeInt(1);
                book.writeToParcel(data, 0);
            } else {
                data.writeInt(0);
            }
            remote.transact(Stub.TRANSAVTION_addBook, data, replay, 0);
            replay.readException();
        } finally {
            replay.recycle();
            data.recycle();
        }
    }

    @Override
    public IBinder asBinder() {
        return remote;
    }
}
